import Ajax from "@/utils/request";
import userStore from '@/store/user'
import { ElMessage } from 'element-plus'
import router from "@/router";
import storage from "@/utils/storage";
import type { AxiosRequestConfig } from 'axios'
export * as user from './user'

const service = new Ajax({
    baseURL: import.meta.env.VITE_BASEURL,
    timeout: 10000,
    interceptors: {
        reqUse(config) {
            const token = userStore().token
            if(token) {
                config.headers!.Authorization = token
            }
            config.headers!.Authorization = `eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIwMDAwMDEifQ.Llik5MSIlrbwk0DBmJCOdms8WayGVHu6wArzfdrYHEwPdx7GX7BQAA-90mBtegrYHAsYmT9FXJ8Dd98GUpqwgQ`
            return config
        },
        resUse(res) {
            const code = res.data.code
            switch (code) {
                case 401:
                    if(!userStore().isExpire) {
                        userStore().isExpire = true
                        userStore().token = ''
                        storage.removeItem('token')
                        ElMessage.error('请先登录或登录状态已过期')
                        router.replace(`/login?redirect=${router.currentRoute.value.fullPath}`)
                        return Promise.reject('请先登录或登录状态已过期')
                    }
                    break;
                case 403:
                    return router.replace(`/`)
                    break;
                case 500:
                    return Promise.reject(res.data.msg)
                    break;
            }
            return res
        },
        resErr(err) {
            return Promise.reject(err)
        }
    }
})

export default function<T = any> (config: AxiosRequestConfig) {
    return service.instance(config).then((res) => {
        return res.data as T
    })
}
